from django.contrib import admin
from .models import Publisher, Author, Book

def upper_case_name(obj):
    return ("%s %s" % (obj.first_name, obj.last_name)).upper()
upper_case_name.short_description = 'Name'

def my_url(obj):
    return ('<a href="http://www.baidu.com">')

class AuthorAdmin(admin.ModelAdmin):
    #list_display = ('first_name', 'last_name', 'email')
    list_display = (upper_case_name, my_url)
    search_fields = ('first_name', 'last_name')
    save_as = True

    '''
    def change_view(self, request, object_id, form_url='', extra_context=None):
        extra_context = extra_context or {}
        extra_context['osm_data'] = self.get_osm_info()
        return super(AuthorAdmin, self).change_view(request, object_id, form_url, extra_context=extra_context)
    '''

    def save_model(self, request, obj, form, change):
        if change:
            obj_original = self.model.objects.get(pk=obj.pk)
            if obj_original.first_name == form._raw_value('first_name'):
                obj.save()
        else:
            obj_original = None
            obj.save()

        print 'change: ', change
        if obj_original != None:
            print obj_original.first_name
        print form._raw_value('first_name')



        #print type(form)

        #print form.objects.get(name='Mike Royko')
        #self.first_name='000000000'

        #obj.user = request.user
        #obj.save()
    '''
    def change_view(self, request, object_id, form_url='', extra_context=None):
        result_template = super(AuthorAdmin, self).change_view(request, object_id, form_url, extra_context)
        result_template['location'] = '/admin/books/book/'
        return result_template
    '''


class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'publisher', 'publication_date')
    list_filter = ('publication_date', )
    date_hierarchy = 'publication_date'
    ordering = ('-publication_date', )
    #fields = ('title', 'author', 'publisher', 'publication_date')
    filter_horizontal = ('author', )
    raw_id_fields = ('publisher', )
    save_as = True

admin.site.register(Publisher)
admin.site.register(Author, AuthorAdmin)
admin.site.register(Book, BookAdmin)


